package com.atguigu.baku.service.impl;

import com.atguigu.baku.entity.Company;
import com.atguigu.baku.entity.PageBean;
import com.atguigu.baku.mapper.CompanyMapper;
import com.atguigu.baku.service.CompanyService;
import com.atguigu.baku.utils.AreaUtils;
import com.atguigu.baku.utils.TimeUtils;
import com.atguigu.baku.vo.AreaCityVo;
import com.atguigu.baku.vo.CompanyListQuery;
import com.atguigu.baku.vo.CompanyListVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 企业主表（工商信息、账户信息） 服务实现类
 * </p>
 *
 * @author dayouzi
 * @since 2022-11-09
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Override
    public Company getCompanyById(String id) {
        return companyMapper.getCompanyById(id);
    }

    @Override
    public PageBean<CompanyListVo> getCompanyList(Integer page, Integer pageSize, CompanyListQuery companyListQuery) {
        //用于返回
        List<CompanyListVo> companyListVos = new ArrayList<>();

        //设置注册资金
        companyListQuery.setCapitalMoneyMin(companyListQuery.getCapitalMoneyMin() * 10000);
        companyListQuery.setCapitalMoneyMax(companyListQuery.getCapitalMoneyMax() * 10000);

        //设置成立时间
        Map dateEstaMap = TimeUtils.getDateEsta(companyListQuery.getDateEsta());
        companyListQuery.setDateEstaMin(dateEstaMap.get("min").toString());
        companyListQuery.setDateEstaMax(dateEstaMap.get("max").toString());

        //查询
        PageInfo<Company> pageInfo = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> {
            companyMapper.getCompanyList(companyListQuery);
        });

        //处理查询结果
        long total = pageInfo.getTotal();
        List<Company> companyList = new ArrayList<>(pageInfo.getList());
        companyList.forEach(company -> {
            CompanyListVo companyListVo = new CompanyListVo();
            //获取城市名称
            Map areaCityMap = AreaUtils.getAreaCityId(company.getAddress());
            BeanUtils.copyProperties(company, companyListVo);
            companyListVo.setCity(areaCityMap.get("city").toString());
            companyListVos.add(companyListVo);
        });

        //处理返回结果
        PageBean<CompanyListVo> pageBean = new PageBean<>(companyListVos);
        pageBean.setTotal(total);
        return pageBean;
    }

    @Override
    public Map<String, Long> getIsCleanNum() {
        return companyMapper.getIsCleanNum();
    }
}
